package com.srwl.mytx.contrack;


import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.MLOC;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.converter.MyRequestBodyConverter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.ConversationData;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.greendao.DaoSession;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.IMImageUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;


import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2018/2/22 0022.
 */

public class RegisterPresenterImpl implements RegisterContrack.Presenter {
    private static final String TAG = "RegisterPresenter";
    private RegisterContrack.View view;
    private Context context;
    private int count = 120;

    public RegisterPresenterImpl(@NonNull RegisterContrack.View view, @NonNull Context context) {
        this.view = view;
        // view.setPresenter(this);
        this.context = context;
    }

    @Override
    public void start() {

    }

    @Override
    public void register(final User registerUser, String mobileCode) {
        //注册按键屏蔽
        view.setRegisterButtonStatus(false);

        view.showProgressDialog(context.getString(R.string.Is_the_registered));
        RetrofitManager
                .getInstance()
                .createRequest(UserService.class)
                .register(mobileCode, registerUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {


                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.d(TAG, response.code() + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            view.disMissProgressDialog();
                            //注册按键恢复
                            view.setRegisterButtonStatus(true);
                            return;
                        }


                        //注册出错
                        if (commonResult.isError()) {
                            view.disMissProgressDialog();
                            //注册按键恢复
                            view.setRegisterButtonStatus(true);
                            Log.e(TAG, commonResult.getStatus() + commonResult.getMsg());
                            switch (commonResult.getStatus()) {
                                case Constant.MOBILE_CODE_ERROR:
                                    view.showToast(context.getString(R.string.mobile_code_error));
                                    view.showRegisterFail();
                                    break;
                                case Constant.MOBILE_CODE_EXPIRE:
                                    view.showToast(context.getString(R.string.mobile_code_expire));
                                    view.showRegisterFail();
                                    break;
                                case Constant.MOBILE_CODE_USED:
                                    view.showToast(context.getString(R.string.mobile_code_used));
                                    view.showRegisterFail();
                                    break;
                                case Constant.SEND_MOBILE_CODE_FAIL_ENGAGED:
                                    ConfirmDialog dialog = new ConfirmDialog(context, "提示", context.getString(R.string.phone_number_engaged));
                                    dialog.show();
                                    view.showSendMobileCodeFail();
                                    view.showRetrievePassWord();
                                    break;
                                default:
                                    view.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }
                        if (commonResult.getData() == null) {
                            view.disMissProgressDialog();
                            return;
                        }
                        JSONObject data = (JSONObject) commonResult.getData();
                        if (data.containsKey("serviceTime")) {
                            MyApplication.timeOffset = data.getLong("serviceTime") - System.currentTimeMillis();
                        }


                        //如果是临时用户 需要把会话表和消息表里面的内容复制出来备用
                        List<ConversationData> tempUserConversationDataList = null;
                        List<Message> tempUserMessages = null;
                        User tempUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
                        if (Utils.isTempUser(tempUserInfo)) {
                            DaoSession daoSession = DBManager.getInstance().getDaoSession();
                            tempUserMessages = daoSession.getMessageDao().loadAll();
                            tempUserConversationDataList = daoSession.getConversationDataDao().loadAll();
                        }

                        //调用一次 登出，是为了当临时用户跳转到登录页面，并登录成功后，清除临时用户的数据
                        Helper.getInstance().reset();
                        // Helper.getInstance().logout();
                        //注册成功
                        // view.setRegisterButtonStatus(false);
                        view.showToast(context.getString(R.string.register_success));
                        //获取返回的用户数据
                        Log.d(TAG, "注册完成：" + data.toString());
                        User user = JSON.parseObject(data.getString("userInfo"), User.class);
                        //持久化用户数据
                        UserProfileManager.getInstance().syncLoginUserInfo(user);
                        Contact tempContact = data.getObject("contact", Contact.class);
                        try {
                            DaoSession daoSession = DBManager.getInstance().getDaoSession();
                            ContactDao contactDao = daoSession.getContactDao();
                            contactDao.insertOrReplace(tempContact);
                            User tempContactUser = tempContact.getUser();
                            if (tempContactUser != null) {
                                DBManager.getInstance().getDaoSession().getUserDao().insertOrReplaceInTx(tempContactUser);
                            }

                            if (tempUserMessages != null && tempUserMessages.size() != 0) {//把临时用户的聊天信息插入新注册用户的 消息表中
                                for (Message tempUserMessage : tempUserMessages) {//把临时用户发出的消息的发送人，替换 成正式用户的 用户id
                                    if (TextUtils.equals(tempUserMessage.getFromId(), tempUserInfo.getuId())) {
                                        tempUserMessage.setFromId(user.getuId());
                                    }
                                }
                                daoSession.getMessageDao().insertOrReplaceInTx(tempUserMessages);
                            }
                            if (tempUserConversationDataList != null && tempUserConversationDataList.size() != 0) {//把临时用户的会话信息插入新注册用户的 会话表中
                                daoSession.getConversationDataDao().insertOrReplaceInTx(tempUserConversationDataList);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        registerUser.setUId(user.getUId());

                        //后端回传的视频和图片地址
                        if (data.containsKey("topic_video_pre")) {
                            AliOssService.TOPIC_VIDEO_PRE_URL = data.getString("topic_video_pre");
                        }
                        if (data.containsKey("topic_image_pre")) {
                            AliOssService.TOPIC_IMAGE_PRE_URL = data.getString("topic_image_pre");
                        }
                        if (data.containsKey("live_host")){
                            MLOC.LIVE_HOST=data.getString("live_host");
                        }
                        view.showRegisterSuccess();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        //注册按键恢复
                        view.setRegisterButtonStatus(true);
                    }
                });
    }

    @Override
    public void pickAvatar() {

    }


    /**
     * 上传头像到服务端，因为注册activity 要销毁，
     * 所以该线程不能和注册activity互相持有变量
     */
    @Override
    public void uploadAvatar() {

        String path = Helper.getInstance().getBasePath() + File.separator + context.getString(R.string.avatar_name);
        String fileName = IMImageUtils.genImageName();
        //上传头像到阿里云
        AliOssService.getInstance().uploadUserAvatar(fileName, path, new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {

            }

            @Override
            public void onSuccess(String objectKey) {
                Log.d(TAG, "onUploadComplete: 头像上传完成" + objectKey);
                //组合成完整的远程地址，因为头像加载的地方很多，如果仅仅是用key,每次用的时候去组合，将非常麻烦，需要修改的地方太多了
                String fullUrl = AliOssService.USER_AVATAR_PRE_URL + objectKey;
                saveToService(fullUrl);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e(TAG, "onFailure: 上传头像文件失败" + message);

            }
        });

//        new Thread(new Runnable() {
//            @Override
//            public void run() {


        //自建图片服务器
//                //读取本地图片输入流
//                FileInputStream inputStream = null;
//                byte[] buff = null;
//                try {
//                    inputStream = new FileInputStream(path + imageName);
//                    int i = inputStream.available();
//                    //byte数组用于存放图片字节数据
//                    buff = new byte[i];
//                    inputStream.read(buff);
//                    //记得关闭输入流
//                    inputStream.close();
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                    return;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    return;
//                }
//
//                final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), buff);
//                RetrofitManager
//                        .getInstance()
//                        .createRequest(UserService.class)
//                        .saveAvatar(requestBody, UserProfileManager.getInstance().getLoginUserInfo().getuId())
//                        .enqueue(new Callback<CommonResult>() {
//                            @Override
//                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
//                                if (!response.isSuccessful()) {
//                                    return;
//                                }
//                                CommonResult body = response.body();
//                                if (body.isOK()) {
//                                    String avatarUrl = body.getData().toString();
//                                    Helper.getInstance().getUserProfileManager().setUserAvatar(avatarUrl);
//                                    Log.d(TAG, avatarUrl);
//                                }
//
//                            }
//
//                            @Override
//                            public void onFailure(Call<CommonResult> call, Throwable t) {
//
//                            }
//                        });

//            }
//        }).start();
    }

    /**
     * 上传完整地址到 服务器
     *
     * @param fullUrl
     */
    private void saveToService(String fullUrl) {


        //url 后面加个时间戳的无用参数，是为了让glide知道图片已经更新了，
        // 本来glide提供了.signature的方法来标识是否更新了图片，但是我用了没效果，

        UserProfileManager.getInstance().setUserAvatar(AliOssService.USER_AVATAR_PRE_URL + fullUrl);
        User user = new User();
        user.setAvatar(fullUrl);
        //把图片地址保存到服务端
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .updateUserInfo(user)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }


                        Log.i(TAG, "onResponse: 头像地址保存到服务端完成");
                        UserProfileManager.getInstance().setUserAvatar(fullUrl);
                        //广播发送者
                        LocalBroadcastManager localBroadcastManager;
                        localBroadcastManager = LocalBroadcastManager.getInstance(context);
                        localBroadcastManager.sendBroadcast(new Intent(Constant.ACTION_HEAD_LOAD));


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: 头像地址保存到服务端失败" + t.getMessage());
                    }
                });
    }

    @Override
    public void sendMobileCode(String phoneNumber) {
        view.setSendMobileCodeButtonStatus(false);
        view.showProgressDialog(context.getString(R.string.mobile_code_sending));
        RetrofitManager
                .getInstance()
                .createRequest(UserService.class)
                .sendMobileCode(phoneNumber)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        view.disMissProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            view.setSendMobileCodeButtonStatus(true);
                            view.showToast(context.getString(R.string.system_busy));
                            view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        // 如果短信发送成功
                        if (result.isOK()) {
                            view.showToast(context.getString(R.string.SMScode_sended));

                            //短信验证码按键倒计时
                            startCount();
                            return;
                        }
                        //如果短信没发送成功，重置按键为可用状态
                        view.setSendMobileCodeButtonStatus(true);
                        view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                        Log.e(TAG, "onResponse: " + result.getMsg());
                        switch (result.getStatus()) {
                            case Constant.SEND_MOBILE_CODE_FAIL_HAVE_NO_COUNT:
                                // view.showToast(String.format(context.getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                ConfirmDialog dialog1 = new ConfirmDialog(context, "提示", String.format(context.getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                dialog1.show();
                                view.showSendMobileCodeFail();
                                return;
                            case Constant.SEND_MOBILE_CODE_FAIL_ENGAGED:
                                //view.showToast(context.getString(R.string.phone_number_engaged));
                                ConfirmDialog dialog = new ConfirmDialog(context, "提示", context.getString(R.string.phone_number_engaged));
                                dialog.show();
                                view.showSendMobileCodeFail();
                                view.showRetrievePassWord();
                                return;


                            case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                view.showToast("手机号格式错误");
                                view.showSendMobileCodeFail();
                                return;

                            default:

                                view.showToast(context.getString(R.string.system_busy));

                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        view.showToast(context.getString(R.string.system_busy));
                        view.setSendMobileCodeButtonStatus(true);
                    }
                });
    }


    public void startCount() {
        count = 120;
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

                if (count > 0) {
                    view.setSendMobileCodeButtonText(count + "");
                    count--;
                } else {
                    timer.cancel();
                    view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                    view.setSendMobileCodeButtonStatus(true);

                }
            }
        };
        timer.schedule(task, 0, 1000);
    }
}
